<template>
  <!-- UpdateMembershipInfo 更新入会资料 -->
  <PageContainer>
    <view class="container">
      <FullLoading :full-loading="isFullLoading" />
      <Header title="入会资料" :is-box-shadow="false" />
      <ApplicationInfo :info="applyInfo" />
      <view class="form-view">
        <ApplyForm
          v-if="isInit"
          :form-item-map="FormItemMap"
          :answer-list="AnswerList"
          :auditStatus="applyInfo?.auditStatus"
          @on-submit="submit"
          @on-load="formOnload"
          @on-change="onChange"
        />
      </view>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  UpdateMembershipInfo  更新入会资料 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { ShareTypeEnum } from '@/enums/shareEnum';
  import { onPullDownRefresh, onShareAppMessage } from '@dcloudio/uni-app';
  import ApplicationInfo from './components/applicationInfo.vue';
  import { onLoad, redirectTo } from '@/router';
  import { isArray, isLogin } from '@/utils/is';
  import { ref } from 'vue';
  import FullLoading from '@/components/FullLoading/index.vue';
  import { Toast, authOfficialAccount } from '@/utils';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import { getMemberInfo, updateMemberInfo } from '@/api/membership';
  import { type customFormUserAnswerList, type MemberInfoResult } from '@/api/membership/types';
  import ApplyForm from './applyForm.vue';
  import { type FormItemVoMapItem } from '@/api/membership/formCompTypes';
  import { toSelectiveType as dynamicToSelectiveType } from '@/utils/dynamicConfig';
  import { type OnchangeArgument } from '@/components/Form/types';
  import { useAppShare } from '@/hooks/core/useAppShare';

  const { hasShareImgConfig } = useAppStoreWithOut();
  const { setWxSharePath } = useAppShare();

  const applyInfo = ref<MemberInfoResult>();
  const isFullLoading = ref(true);

  const FormItemMap = ref<FormItemVoMapItem>({});
  const AnswerList = ref<customFormUserAnswerList[]>([]);
  const isInit = ref(false);

  const companyId = ref<number>();

  async function __init() {
    isFullLoading.value = true;
    isInit.value = false;
    try {
      const res = await getMemberInfo();
      companyId.value = res.companyId;
      FormItemMap.value = res.customFormItemMap;
      AnswerList.value = res.customFormUserAnswerList;
      applyInfo.value = res;
      isInit.value = true;
      uni.stopPullDownRefresh();
    } catch (error) {
      setTimeout(() => {
        dynamicToSelectiveType(
          {
            linkUrl: 'selectiveType',
            isRedirectTo: true,
          },
          () => {},
          true,
        );
      }, 2000);
    }
  }

  function onChange(op: OnchangeArgument) {
    const { val } = op;
    if (val) {
      companyId.value = val?.id;
    }
  }

  function formOnload() {
    isFullLoading.value = false;
  }

  function submit(vals: { [x: string]: any }) {
    const result = [];
    for (const key in vals) {
      let content = vals[key];
      if (!isArray(content)) content = content.toString().split(',');
      result.push({
        formItemId: Number(key),
        content,
      });
    }

    updateMemberInfo({ companyId: companyId.value, customMemberInfoAnswerList: result }).then(() =>
      successCallBack(),
    );
  }

  async function successCallBack() {
    try {
      await authOfficialAccount();
    } catch (error) {}
    redirectTo({ name: 'updateMembershipInfoResult' });
    // Toast({
    //   title: '资料已提交，请等待管理员审核。',
    //   icon: 'none',
    // });
    // isFullLoading.value = true;
    // __init();
  }

  onLoad(() => {
    isLogin(__init, true);
  });

  onPullDownRefresh(() => __init());

  onShareAppMessage(() => {
    const membershipShare = hasShareImgConfig(ShareTypeEnum.membership);
    return {
      imageUrl: membershipShare?.iconUrl,
      path: setWxSharePath({ name: 'updateMembershipInfo' }),
      title: membershipShare?.desc,
    };
  });
</script>

<style lang="scss" scoped>
  .container {
    padding-top: 30rpx;
  }
</style>
